package com.fulihui.common.conv;

import com.fulihui.common.util.DateUtils;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Bean工具类，支持字符串转date，data转字符串
 *
 * @auther: Levon
 * @version: V 0.1 2017-12-12 14:43
 */
public class BeanUtil {

    public static <T> T copy(Object source, Class<T> clazz) {
        T target = BeanConv.copy(source, clazz);
        dateConvert(source, target);
        return target;
    }

    public static <T> T copy(Object source, Class<T> clazz, String... ignoreProperties) {
        T target = BeanConv.copy(source, clazz, ignoreProperties);
        dateConvert(source, target);
        return target;
    }

    public static <T, S> List<T> copy(List<S> sourceList, Class<T> clazz) {
        return BeanConv.copy(sourceList, clazz);
    }

    public static <T, S> List<T> copy(List<S> sourceList, Class<T> clazz, String... ignoreProperties) {
        return BeanConv.copy(sourceList, clazz, ignoreProperties);
    }

    private static void dateConvert(Object source, Object target) {
        if (Objects.isNull(source)) {
            return;
        }
        Class sourceClazz = source.getClass();
        Class targetClazz = target.getClass();

        Field[] fields = sourceClazz.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Object sourceFieldObj = field.get(source);

                String sourceName = field.getName();
                Field targetField = targetClazz.getDeclaredField(sourceName);

                targetField.setAccessible(true);
                Class<?> fielType = targetField.getType();

                if (sourceFieldObj instanceof Date) {
                    Date date = (Date) sourceFieldObj;
                    targetField.set(target, DateUtils.formatNewFormat(date));
                } else if (sourceFieldObj instanceof String && fielType == Date.class) {
                    targetField.set(target, DateUtils.parseNewFormat(sourceFieldObj.toString()));
                }
            } catch (Exception e) {
            }
        }
    }

}
